package lab.jsp;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import lab.jsp.util.ConnectionUtil;

/**
 *
 * @author Smike
 */
public abstract class AbstractJSP<T> extends HttpServlet implements HttpJspPage {

    Connection connection;
    
    protected Connection getConnection() {
        if (connection == null) {
            connection = ConnectionUtil.getConnection();
            assert connection != null;
        }
        return connection;
    }
    
    protected abstract T getData();
    
    public void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException ex) {
                Logger.getLogger(AbstractJSP.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        _jspService(request, response);
        closeConnection();
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        _jspService(request, response);
    }

    @Override
    public void jspInit() {
        connection = ConnectionUtil.getConnection();
    }

    @Override
    public void jspDestroy() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(AbstractJSP.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    
    
    

}
